package cn.bb.bbstudy.config;

import cn.bb.bbstudy.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserServiceImpl userService;//注意这里是实现类

    @Autowired
    private DataSource dataSource;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //用户授权认证
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //拦截配置
        http.authorizeRequests()
                .antMatchers("/","/index","/register","/login","/toLogin","/invite").permitAll()
                .antMatchers("/*").authenticated();

        //登录配置
        http.formLogin()
                //登录页面
                .loginPage("/toLogin")
                //登录提交表单的请求
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/index");


        //X-Frame-Options 用来告诉浏览器，页面能不能以 frame、 iframe、 object 形式嵌套在其他站点中，
        // 用来避免点击劫持(clickjacking)攻击。
        http.headers().contentTypeOptions().disable();
        http.headers().frameOptions().disable(); // 图片跨域
        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
        // 注销配置
        http.logout().logoutSuccessUrl("/");

        //记住我
        http.rememberMe()
                .userDetailsService(userService)
                //过7天过期
                .tokenValiditySeconds(60*60*24*7)
                .tokenRepository(jdbcTokenRepository());

    }

    /**
     * 记住我的配置
     * @return
     */
    @Bean
    public PersistentTokenRepository jdbcTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        //自动注入mysql的DataSource
        jdbcTokenRepository.setDataSource(dataSource);
        //第一次启动自动创建 第二次启动需要注释
//        jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
